<?php
class orderModel extends RPHP_Model
{
    protected $appid  = 10001;
    protected $appkey = 'c6e905290fb1ff6931faba9494564438';

    //用户订单数量统计
    public function getOrderCountByType($is_pat = 0)
    {
        $count['order_count']       = 0;
        $count['not_pay_count']     = 0;
        $count['send_count']        = 0;
        $count['sended_count']      = 0;
        $count['rebackapply_count'] = 0;

        $where = "";
        if ($is_pat > 0) {
            $where = " AND `sell_type`=4";

        }
        $sql  = "SELECT `pay_status`,`order_status`,`shipping_status`,`is_comment` FROM {$this->_prefix['primary']}order_info WHERE `uid`=" . $this->_user['uid'] . $where;
        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                //待付款
                if ($r['pay_status'] == 0 && $r['order_status'] == 0) {
                    $count['not_pay_count'] += 1;
                }
                //待发货
                elseif ($r['pay_status'] == 2 && $r['order_status'] == 1 && ($r['shipping_status'] == 0 || $r['shipping_status'] == 3 || $r['shipping_status'] == 5)) {

                    $count['send_count'] += 1;
                }
                //待收货
                elseif ($r['pay_status'] == 2 && $r['shipping_status'] == 1) {

                    $count['sended_count'] += 1;
                }
                //退货退款
                elseif ($r['pay_status'] == 3 || $r['pay_status'] == 5 || $r['shipping_status'] == 7 || $r['shipping_status'] == 4) {

                    $count['rebackapply_count'] += 1;
                }
                //全部（不含取消）
                elseif ($r['order_status'] !== 2) {

                    $count['order_count'] += 1;
                }
            }

            //全部订单
            $count['order_count'] = count($data);
        }

        return $count;

    }

    // 获取单个订单
    public function getSingleOrder($order_id, $uid = 0, $transaction_type = 1)
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}order_info WHERE `order_id`=" . intval($order_id) . " AND `uid`=" . intval($uid) . " ORDER BY `order_id` DESC LIMIT 1";

        $data = $this->db->getrow($sql);

        //如果支付环境变化了
        if ($data && $data['transaction_type'] != $transaction_type) {
            $sql = "UPDATE {$this->_prefix['primary']}order_info SET `transaction_type`=" . $transaction_type . " WHERE `order_id`=" . $data['order_id'] . " AND `transaction_type`>1";
            $this->sql($sql);
        }
        return $data;
    }
    //获得订单中的单个商品信息
    public function getOrderGoodsDetail($rec_id)
    {

        $sql  = "SELECT * FROM {$this->_prefix['primary']}order_goods WHERE `rec_id`=" . intval($rec_id);
        $data = $this->db->getrow($sql);
        return $data;
    }
    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }

    //获取用户订单
    public function getOrderList($para, $page = 1, $pagesize = 10)
    {
        $where = " `uid`=" . $this->_user['uid'];

        if ($para) {

            if ($para['order_id'] != "") {
                if (strlen($para['order_id']) > 10) {
                    $where .= " AND `order_sn`='" . $para['order_id'] . "'";
                } else {
                    $where .= " AND order_id=" . $para['order_id'];
                }

            }

            if ($para['type'] == 1) {
                //待付款
                $where = " `uid`=" . $this->_user['uid'] . " AND pay_status=0 and order_status=0";
            } elseif ($para['type'] == 2) {
                //待发货
                //$where .= " AND order_status=1 AND shipping_status in(0,4)  AND pay_status=2";
                $where .= " AND order_status=1 AND shipping_status IN (0,3,5) AND pay_status=2";
            } elseif ($para['type'] == 3) {
                //待收货
                //$where .= " AND shipping_status IN(1,6) AND pay_status=2";
                $where .= " AND order_status=1 AND shipping_status IN (1,3,4,7) AND pay_status IN (2,5,6)";

            }
//            elseif ($para['type'] == 4) {
            ////待评价
            //                $where .= " AND shipping_status IN (2,9) AND pay_status=2 and is_comment=0";
            //            }
            elseif ($para['type'] == 5) {
                //售后
                //$where .= "  AND shipping_status =7 AND pay_status =3";
                $where .= "  AND (shipping_status IN (4,7) OR pay_status IN (3,5))";
            }

            if ($para['is_pat']) {

                $where .= "  AND `sell_type`=4";
            }
            if ($para['keyword'] != '') {
                $where .= "  AND `order_id`='%" . $para['keyword'] . "%'";
            }

        }

        $sql = "SELECT COUNT(`order_id`) AS `cnt` FROM {$this->_prefix['primary']}order_info WHERE " . $where;
        $cnt = $this->sql($sql);
        $rs  = array();
        if ($cnt[0]['cnt'] > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`add_time` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}order_info WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            if ($rs) {
                foreach ($rs as $key => $val) {

                    if ($val['province_id'] > 0) {
                        $region_ids[] = $val['province_id'];
                    }

                    if ($val['city_id'] > 0) {
                        $region_ids[] = $val['city_id'];
                    }

                    if ($val['county_id'] > 0) {
                        $region_ids[] = $val['county_id'];
                    }

                    if ($val['pay_status'] == 0 && $val['order_status'] == 0) {
                        $rs[$key]['new_status'] = '待付款';
                    } elseif ($val['pay_status'] == 0 && $val['order_status'] == 2) {
                        $rs[$key]['new_status'] = '已取消';
                    }
//                    elseif ($val['order_status'] == 1 && ($val['shipping_status'] == 0 || $val['shipping_status'] == 4) && $val['pay_status'] == 2) {
                    //                        $rs[$key]['new_status'] = '待发货';
                    elseif ($val['order_status'] == 1 && $val['shipping_status'] == 3 && $val['pay_status'] == 2) {
                        $rs[$key]['new_status'] = '部分发货';
                    } elseif ($val['order_status'] == 1 && $val['shipping_status'] == 5 && $val['pay_status'] == 2) {
                        $rs[$key]['new_status'] = '发货中';
                    } elseif ($val['order_status'] == 1 && $val['shipping_status'] == 0 && $val['pay_status'] == 2) {
                        $rs[$key]['new_status'] = '待发货';
                    } elseif ($val['order_status'] == 8) {
                        $rs[$key]['new_status'] = '交易关闭';
                    }
//                    elseif (($val['shipping_status'] == 1 || $val['shipping_status'] == 6) && $val['pay_status'] == 2) {
                    //                        $rs[$key]['new_status'] = '待收货';
                    elseif ($val['shipping_status'] == 1 && $val['pay_status'] == 2) {
                        $rs[$key]['new_status'] = '待收货';
                    } /* elseif (($val['shipping_status'] == 2 || $val['shipping_status'] == 9) && $val['pay_status'] == 2 && $val['is_comment'] == 0) {
                    $rs[$key]['new_status'] = '待评价';
                    } */elseif ($val['order_status'] == 7) {
                        $rs[$key]['new_status'] = '已完成';
                    } elseif ($val['shipping_status'] == 4 && $val['pay_status'] > 0) {
                        $rs[$key]['new_status'] = '部分退货中';
                    } elseif ($val['shipping_status'] == 7 && $val['pay_status'] > 0) {
                        $rs[$key]['new_status'] = '退货中';
                    } elseif ($val['pay_status'] == 3) {
                        $rs[$key]['new_status'] = '退款中';
                    } elseif ($val['pay_status'] == 5) {
                        $rs[$key]['new_status'] = '部分退款中';
                    } elseif ($val['pay_status'] == 4) {
                        $rs[$key]['new_status'] = '已退款';
                    }
                    /*   elseif ($val['shipping_status'] == 10 && $val['pay_status'] == 5) {
                    $rs[$key]['new_status'] = '申请已同意';
                    //取退换地址：
                    $sql  = "SELECT * from {$this->_prefix['primary']}member_rgaddress WHERE shopid=" . $val['shopid'] . " and is_used=1 limit 1";
                    $info = $this->db->getrow($sql);
                    if ($info) {
                    if ($info['province_id'] > 0) {
                    $region_idss[] = $info['province_id'];
                    }

                    if ($info['city_id'] > 0) {
                    $region_idss[] = $info['city_id'];
                    }

                    if ($info['county_id'] > 0) {
                    $region_idss[] = $info['county_id'];
                    }

                    if ($region_idss) {
                    $regions = $this->getRegionWithId($region_idss);
                    }

                    $rs[$key]['reback_address'] = $regions[$info['province_id']] . $regions[$info['city_id']] . $regions[$info['county_id']] . $info['address'];
                    }
                    }  */
                    $rs[$key]['create_time'] = date('Y-m-d H:i:s', $val['add_time']);
                    $sql                     = "SELECT og.*,gd.`thumb_docid` FROM {$this->_prefix['primary']}order_goods og INNER JOIN  {$this->_prefix['primary']}goods_data gd ON  og.`order_id`=" . $val['order_id'] . " AND og.goods_id = gd.goods_id";

                    $rows = $this->sql($sql);
                    if ($rows) {
                        
                        foreach ($rows as $kk=>$r) {
                            if ($r['thumb_docid'] > 0) {
                                $docid[] = $r['thumb_docid'];
                            }

                            if ($r['stock_id']) {
                                $rows[$kk]['attr_str'] = $this->table('goods_affi_spec')->findOneBySql('`stock_id`='.$r['stock_id'],'spec_name');
                            }else{
                                $rows[$kk]['attr_str'] = '';
                            }

                        }

                        $rs[$key]['goods'] = $rows;
                        // var_dump($rows);exit;

                    }
                    if ($val['shopid'] != $val['channel_shopid']) {
                        $rs[$key]['channel_shippingfee'] = $this->getChannelShippingFee($val['channel_shopid'], count($rows));
                        $shopfee                         = $this->getShippingFee($val['goods_amount'], count($rows));
                        $rs[$key]['shop_shippingfee']    = $shopfee['shipping_fee'];
                    }
                }

                if ($region_ids) {
                    $region = $this->getRegionWithId($region_ids);
                }

                if ($docid) {
                    $docs = $this->getDocs($docid);
                }

            }

        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt[0]['cnt'] / $pagesize),
            'count'   => $cnt[0]['cnt'],
            'data'    => $rs,
            'para'    => $para,
            'docs'    => $docs,
            'region'  => $region,
        );
    }
    //获取订单详情
    public function getOrderDetail($order_id)
    {
        $sql        = "SELECT * FROM {$this->_prefix['primary']}order_info WHERE order_id=" . $order_id . " AND  `uid`=" . $this->_user['uid'];
        $order_info = $this->db->getrow($sql);
        if ($order_info) {
            $sql  = "SELECT og.*,gd.`thumb_docid` FROM {$this->_prefix['primary']}order_goods og INNER JOIN  {$this->_prefix['primary']}goods_data gd ON  og.`order_id`=" . $order_id . " AND og.goods_id = gd.goods_id";
            $rows = $this->sql($sql);
            if ($rows) {
                
                foreach ($rows as $kk=>$r) {
                    if ($r['thumb_docid'] > 0) {
                        $docid[] = $r['thumb_docid'];
                    }

                    if ($r['stock_id']) {
                        $rows[$kk]['attr_str'] = $this->table('goods_affi_spec')->findOneBySql('`stock_id`='.$r['stock_id'],'spec_name');
                    }else{
                        $rows[$kk]['attr_str'] = '';
                    }

                }

                $order_info['goods'] = $rows;

            }
            if ($order_info['province_id'] > 0) {
                $region_ids[] = $order_info['province_id'];
            }

            if ($order_info['city_id'] > 0) {
                $region_ids[] = $order_info['city_id'];
            }

            if ($order_info['county_id'] > 0) {
                $region_ids[] = $order_info['county_id'];
            }

            if ($order_info['pay_status'] == 0 && $order_info['order_status'] == 0) {
                $order_info['new_status'] = '待付款';
            } elseif ($order_info['pay_status'] == 0 && $order_info['order_status'] == 2) {
                $order_info['new_status'] = '已取消';
            } elseif ($order_info['order_status'] == 1 && $order_info['shipping_status'] == 3 && $order_info['pay_status'] == 2) {
                $order_info['new_status'] = '部分发货';
            } elseif ($order_info['order_status'] == 1 && $order_info['shipping_status'] == 5 && $order_info['pay_status'] == 2) {
                $order_info['new_status'] = '发货中';
            } elseif ($order_info['order_status'] == 1 && $order_info['shipping_status'] == 0 && $order_info['pay_status'] == 2) {
                $order_info['new_status'] = '待发货';
            } elseif ($order_info['order_status'] == 8) {
                $order_info['new_status'] = '交易关闭';
            } elseif ($order_info['shipping_status'] == 1 && $order_info['pay_status'] == 2) {
                $order_info['new_status'] = '待收货';
            } elseif ($order_info['order_status'] == 7) {
                $order_info['new_status'] = '已完成';
            } elseif ($order_info['shipping_status'] == 4 && ($order_info['pay_status'] == 2 || $order_info['pay_status'] == 5)) {
                $order_info['new_status'] = '部分退货中';
            } elseif ($order_info['shipping_status'] == 7 && ($order_info['pay_status'] == 2 || $order_info['pay_status'] == 3)) {
                $order_info['new_status'] = '退货中';
            } elseif ($order_info['pay_status'] == 3) {
                $order_info['new_status'] = '退款中';
            } elseif ($order_info['pay_status'] == 5) {
                $order_info['new_status'] = '部分退款中';
            } elseif ($order_info['pay_status'] == 4) {
                $order_info['new_status'] = '已退款';
            }

            if ($region_ids) {
                $region = $this->getRegionWithId($region_ids);
            }

            if ($docid) {
                $docs = $this->getDocs($docid);
            }

        }
        //print_r($order_info);die;
        return array(
            'data'   => $order_info,
            'docs'   => $docs,
            'region' => $region,
        );
    }
    // 获取区域信息
    public function getRegion($parent_id = 0)
    {
        $sql = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `parent_id`=" . intval($parent_id);

        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[$r['region_id']] = $r['region_name'];
            }
            return $new;
        } else {
            return false;
        }

    }

    // 获取区域信息
    public function getRegionWithId($region_id)
    {
        if (is_array($region_id)) {
            $tsql = " IN (" . implode(",", $region_id) . ")";
        } else {
            $tsql = "=" . $region_id;
        }

        $sql = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `region_id`" . $tsql;

        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[$r['region_id']] = $r['region_name'];
            }
            return $new;
        } else {
            return false;
        }

    }

    // 获取用户资金
    public function getBalance()
    {
        $sql = "SELECT * FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $this->_user['uid'];
        return $this->db->getrow($sql);
    }

    //取消订单
    public function cancelOrder($order_id)
    {
        $code     = 900;
        $order_id = intval($order_id);
        if ($order_id > 0) {

            $sql   = "SELECT * FROM {$this->_prefix['primary']}order_info WHERE `order_id`=" . $order_id . " AND `uid`=" . $this->_user['uid'] . " AND `order_status`=0 AND `pay_status`=0";
            $order = $this->db->getrow($sql);
            if ($order) {

                $this->db->begin();
                $commit = false;

                // 更新订单信息

                $sql = "UPDATE {$this->_prefix['primary']}order_info SET `order_status`=2 WHERE `order_id`=" . $order['order_id'] . " AND `uid`=" . $this->_user['uid'];
                $rcs = $this->sql($sql);
                if ($rcs) {

                    $commit  = true;
                    $balance = $this->getBalance();
                    // 退货金花、代金券、硒米

                    if ($order['gold_fee'] > 0 && $commit) {
                        $commit = false;

                        $sql  = "UPDATE {$this->_prefix['primary']}finance_balance SET `gold_money`=`gold_money`+" . $order['gold_fee'] . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`random_num`=" . rand(100000, 999999) . " WHERE `uid`=" . $balance['uid'];
                        $upid = $this->sql($sql);
                        if ($upid) {
                            $detail_note = "取消订单号" . $order_sn . "退回金花";
                            $event       = 7;
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $balance['uid'] . "," . $event . "," . $order['gold_fee'] . "," . ($balance['gold_money'] + $order['gold_fee']) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $order_id . ",'order_info')";
                            $detail_id   = $this->sql($sql);
                            if ($detail_id) {
                                $commit = true;

                            } else {

                                $code = 862;
                            }

                        } else {

                            $code = 861;
                        }
                    }

                    if ($order['coupon_fee'] > 0 && $commit) {
                        $commit = false;

                        $sql  = "UPDATE {$this->_prefix['primary']}finance_balance SET `coupon`=`coupon`+" . $order['coupon_fee'] . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`random_num`=" . rand(100000, 999999) . " WHERE `uid`=" . $balance['uid'];
                        $upid = $this->sql($sql);
                        if ($upid) {
                            $detail_note = "取消订单号" . $order_sn . "退回代金券";
                            $event       = 7;
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $balance['uid'] . "," . $event . "," . $order['coupon_fee'] . "," . ($balance['coupon'] + $order['coupon_fee']) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $order_id . ",'order_info')";
                            $detail_id   = $this->sql($sql);
                            if ($detail_id) {
                                $commit = true;

                            } else {

                                $code = 862;
                            }

                        } else {

                            $code = 861;
                        }
                    }

                    if ($order['ximi_fee'] > 0 && $commit) {
                        $commit = false;

                        $sql  = "UPDATE {$this->_prefix['primary']}finance_balance SET `ximi_money`=`ximi_money`+" . $order['ximi_fee'] . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`random_num`=" . rand(100000, 999999) . " WHERE `uid`=" . $balance['uid'];
                        $upid = $this->sql($sql);
                        if ($upid) {
                            $detail_note = "取消订单号" . $order_sn . "退回硒米";
                            $event       = 7;
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $balance['uid'] . "," . $event . "," . $order['ximi_fee'] . "," . ($balance['ximi_money'] + $order['ximi_fee']) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $order_id . ",'order_info')";
                            $detail_id   = $this->sql($sql);
                            if ($detail_id) {
                                $commit = true;

                            } else {

                                $code = 862;
                            }

                        } else {

                            $code = 861;
                        }
                    }

                    // 已经使用的优惠券撤销使用状态
                    $sql  = "SELECT `coupon_id` FROM {$this->_prefix['primary']}discount_coupon WHERE `order_id`=" . $order['order_id'];
                    $tmpc = $this->db->getone($sql);
                    if ($tmpc > 0 && $commit) {
                        $commit = false;

                        $sql  = "UPDATE {$this->_prefix['primary']}discount_coupon SET `status`=0,`order_id`=0,`used_time`=0 WHERE `order_id`=" . $order['order_id'];
                        $rcob = $this->db->sql($sql);
                        if ($rcob > 0) {
                            $commit = true;
                        }
                    }

                    $sql        = "SELECT `goods_id`,`goods_number` FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $order['order_id'];
                    $goods_list = $this->sql($sql);
                    if ($goods_list && $commit) {

                        foreach ($goods_list as $goods) {

                            if ($commit == true) {
                                $sql = "UPDATE  {$this->_prefix['primary']}goods_stock SET `number`=`number`+" . $goods['goods_number'] . " WHERE `goods_id`=" . $goods['goods_id'];
                                $rcq = $this->sql($sql);
                                if ($rcq > 0) {

                                } else {

                                    $commit = false;
                                }
                            }

                        }
                    }

                }

                if ($commit) {
                    $this->db->commit();
                    $code = 200;
                } else {
                    $code = 403;
                }
            } else {
                $code = 404;
            }

        }
        if ($rollback) {
            $this->db->rollback();
        } else {
            $this->db->commit();
        }

        return array(
            'code' => $code,
        );
    }

    //确认收货操作
    public function reveiveOrder($order_id)
    {
        $code     = 900;
        $order_id = intval($order_id);
        if ($order_id > 0) {
            $sql = "UPDATE {$this->_prefix['primary']}order_info SET `shipping_status`=2,`order_status`=7,`receive_time`=" . time() . " WHERE `order_id`=" . $order_id . " AND `uid`=" . $this->_user['uid'] . " AND `shipping_status`>0 AND `pay_status`>0";
            $rs  = $this->sql($sql);
            if ($rs > 0) {
                $code = 200;
                $sql = "UPDATE {$this->_prefix['primary']}order_goods SET `shipping_status`=2  WHERE `order_id`=" . $order_id . " AND `shipping_status`>0";
                $this->sql($sql);
                
            }

        }

        return $code;
    }

    public function getShippingFee($goods_amount, $goods_number)
    {
        $shipping_fee   = 0;
        $shipping_title = "";
        if ($goods_amount && $goods_number) {
            $sql        = "SELECT * from {$this->_prefix['primary']}shipping_tempalte where shopid=" . $this->_user['shopid'] . " limit 1";
            $shipping_t = $this->db->getrow($sql);
            if ($shipping_t) {
                $rule = unserialize($shipping_t['rule']);
                if ($rule['free_money'] > 0) {
                    //有配置免邮金额
                    if ($goods_amount >= $rule['free_money']) {

                        return array("shipping_title" => "满" . $rule['free_money'] . "免运费", "shipping_fee" => 0.00);
                    }

                }
                $first_count = $goods_number - $rule['count'];
                if ($first_count >= 0 && $rule['count'] > 0) {
                    //首件
                    $shipping_fee = $rule['money'];
                }
                if ($first_count > 0 && $rule['add_count'] > 0) {
                    //续件 每增加多少件 需要多少元
                    $s_count = intval($first_count / $rule['add_count']);
                    $shipping_fee += $s_count * $rule['add_money'];

                }
                $shipping_title = "运费" . $shipping_fee . "元";
            }

        }
        return array("shipping_title" => $shipping_title, "shipping_fee" => $shipping_fee);

    }

    public function getChannelShippingFee($shopid, $goods_number)
    {
        $shipping_fee = 0;
        if ($goods_number) {
            $sql        = "SELECT * from {$this->_prefix['primary']}shipping_tempalte where shopid=" . $shopid . " limit 1";
            $shipping_t = $this->db->getrow($sql);
            if ($shipping_t) {
                $rule        = unserialize($shipping_t['rule']);
                $first_count = $goods_number - $rule['count'];
                //首件
                $shipping_fee = $rule['money'];
                if ($first_count > 0 && $rule['add_count'] > 0) {
                    //续件 每增加多少件 需要多少元
                    $s_count = intval($first_count / $rule['add_count']);
                    $shipping_fee += $s_count * $rule['add_money'];

                }
            }

        }
        return $shipping_fee;
    }

    //获取物流信息
    public function getCourier($shipping_id, $shipping_name)
    {
        $code = 403;

        if ($shipping_id != "" && $shipping_name != "") {

            $redis_key = 'LEATIEN_EXPRESS_' . $shipping_id . md5($shipping_name);
            $rele      = $this->redis->get($redis_key);
            if ($rele != "") {
                $code = 200;
                $data = json_decode($rele, true);
            } else {

                $timestamp = $_SERVER['REQUEST_TIME'];
                $st        = md5($this->c['api']['appid'] . $shipping_id . $shipping_name . $timestamp . $this->c['api']['appkey']);
                $url       = "http://api.leatien.com/express/get?appid=" . $this->c['api']['appid'] . "&shipping_name=" . $shipping_name . "&shipping_id=" . $shipping_id . "&timestamp=" . $timestamp . "&st=" . $st;

                $tmpdata = file_get_contents($url);
                if ($tmpdata != "") {
                    $tmpdata = json_decode($tmpdata, true);
                    if ($tmpdata['code'] == 200) {

                        $tmpdata['content']    = unserialize($tmpdata['content']);
                        $data['shipping_id']   = $shipping_id;
                        $data['shipping_name'] = $shipping_name;
                        $data['info']          = $tmpdata['content']['data']['origin_info']['trackinfo'];
                        $code                  = 200;
                        $this->redis->setex($redis_key, 1200, json_encode($data));
                    }
                }

            }

        }

        return array(
            'code' => $code,
            'data' => $data,
        );

    }

    //申请退款
    public function saveOrderRefundStatus_bf($da)
    {
        $code = 403;
        $msg  = "申请退款失败，请重试";
        $this->db->begin();
        $rollback = false;
        $order_id = intval($da['order_id']);
        $rec_id   = intval($da['rec_id']);
        if ($order_id && $rec_id) {

            $sql  = "SELECT * from {$this->_prefix['primary']}order_info WHERE order_id=" . $order_id . " AND `uid`=" . $this->_user['uid'];
            $info = $this->db->getrow($sql);
            //判断是否付款
            if ($info['pay_status'] != 0 && $info['order_status'] == 1) {
                //申请退款操作
                $sql = "UPDATE {$this->_prefix['primary']}order_goods SET `return_time`=" . $_SERVER['REQUEST_TIME'] . ",`refund_status`=1 WHERE `rec_id`=" . $rec_id;
                $rs  = $this->sql($sql);
                if ($rs) {
                    $sql = "SELECT COUNT(`rec_id`) AS `cnt` FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $order_id . " AND refund_status IN (0,5) AND return_goods_status IN (0,7)";
                    $cnt = $this->db->getone($sql);
                    $sql = "SELECT COUNT(`rec_id`) AS `cn` FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $order_id . " AND return_goods_status NOT IN (0,7)";
                    $cn  = $this->db->getone($sql);
                    if ($cnt > 0 || $cn > 0) {
                        $pay_status = 5; //部分退款

                    } else {
                        $pay_status = 3; //全部退款
                    }

                    if ($info['pay_status'] != $pay_status) {
                        $sql   = "UPDATE {$this->_prefix['primary']}order_info SET `pay_status`=" . $pay_status . " WHERE `order_id`=" . $order_id;
                        $re_id = $this->sql($sql);
                        if ($re_id) {
                            $code     = 200;
                            $msg      = "申请退款成功，请耐心等待审核！";
                            $rollback = true;
                        } else {
                            $code = 407;

                        }
                    } else {
                        $code     = 200;
                        $msg      = "申请退款成功，请耐心等待审核！";
                        $rollback = true;

                    }
                } else {

                    $code = 406;
                }
            } else {

                $code = 408;
            }

        } else {

            $code = 405;
        }
        $arr = array();
        if ($rollback) {
            $this->db->commit();

        } else {
            $this->db->rollback();
        }
        $arr['code'] = $code;
        $arr['msg']  = $msg;
        return $arr;

    }

    //申请退款
    public function saveOrderRefundStatus($da)
    {
        $code = 403;
        $msg  = "申请退款失败，请重试";
        $this->db->begin();
        $rollback = false;
        $order_id = intval($da['order_id']);
        $rec_id   = intval($da['rec_id']);
        if ($order_id && $rec_id) {

            $sql  = "SELECT * from {$this->_prefix['primary']}order_info WHERE order_id=" . $order_id . " AND `uid`=" . $this->_user['uid'];
            $info = $this->db->getrow($sql);
            //判断是否付款
            if ($info['pay_status'] == 2 && $info['order_status'] == 1 && $info['shipping_status']==0) {
                //申请退款操作
                $sql = "UPDATE {$this->_prefix['primary']}order_goods SET `return_time`=" . $_SERVER['REQUEST_TIME'] . ",`refund_status`=1 WHERE `order_id`=" . $info['order_id'];
                $rs  = $this->sql($sql);
                if ($rs) {

                    $pay_status = 3; //全部退款
                    $sql   = "UPDATE {$this->_prefix['primary']}order_info SET `pay_status`=" . $pay_status . " WHERE `order_id`=" . $order_id;
                    $re_id = $this->sql($sql);
                    if ($re_id) {
                        $code     = 200;
                        $msg      = "申请退款成功，请耐心等待审核！";
                        $rollback = true;
                    } else {
                        $code = 407;

                    }

                } else {

                    $code = 406;
                }
            } else {

                $code = 408;
            }

        } else {

            $code = 405;
        }
        $arr = array();
        if ($rollback) {
            $this->db->commit();

        } else {
            $this->db->rollback();
        }
        $arr['code'] = $code;
        $arr['msg']  = $msg;
        return $arr;

    }

    public function saveOrderReturnGoodsStatus($da)
    {

        $code = 403;
        $msg  = "申请退货失败，请重试";
        $this->db->begin();
        $rollback = false;
        $order_id = intval($da['order_id']);
        $rec_id   = intval($da['rec_id']);
        if ($order_id && $rec_id) {

            $sql  = "SELECT * from {$this->_prefix['primary']}order_info WHERE order_id=" . $order_id . " AND `uid`=" . $this->_user['uid'];
            $info = $this->db->getrow($sql);
            if ($info['order_status'] == 1 && $info['pay_status'] !== 0) {
                //申请退货操作
                $sql = "UPDATE {$this->_prefix['primary']}order_goods SET `return_time`=" . $_SERVER['REQUEST_TIME'] . ",`return_goods_status`=1 WHERE `rec_id`=" . $rec_id;
                $rs  = $this->sql($sql);
                if ($rs) {
                    $sql = "SELECT COUNT(`rec_id`) AS `cnt` FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $order_id . " AND `refund_status` IN (0,5)  AND  `return_goods_status` IN (0,7)";
                    $cnt = $this->db->getone($sql);
                    $sql = "SELECT COUNT(`rec_id`) AS `cn` FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $order_id . " AND refund_status  NOT IN (0,5)";
                    $cn  = $this->db->getone($sql);

                    if ($cnt > 0 || $cn > 0) {
                        $shipping_status = 4; //部分退货

                    } else {
                        $shipping_status = 7; //全部退货
                    }

                    if ($info['shipping_status'] != $shipping_status) {
                        $sql   = "UPDATE {$this->_prefix['primary']}order_info SET `shipping_status`=" . $shipping_status . " WHERE `order_id`=" . $order_id;
                        $re_id = $this->sql($sql);
                        if ($re_id) {
                            $code     = 200;
                            $msg      = "申请退货成功，请耐心等待审核！";
                            $rollback = true;
                        } else {
                            $code = 407;

                        }

                    } else {
                        $code     = 200;
                        $msg      = "申请退货成功，请耐心等待审核！";
                        $rollback = true;

                    }
                } else {

                    $code = 406;
                }
            } else {

                $code = 408;
            }

        } else {

            $code = 405;
        }
        $arr = array();
        if ($rollback) {
            $this->db->commit();

        } else {
            $this->db->rollback();
        }
        $arr['code'] = $code;
        $arr['msg']  = $msg;
        return $arr;
    }

    //填写快递信息
    public function saveApplyReturnGoodsStatus($da)
    {
        $rec_id               = intval($da['rec_id']);
        $return_shipping_name = trim($da['return_shipping_name']);
        $return_shipping_id   = trim($da['return_shipping_id']);
        $code                 = 403;
        $msg                  = "填写快递信息失败，请重试";
        if (!empty($rec_id) && !empty($return_shipping_name) && !empty($return_shipping_id)) {
            //保存快递信息
            $sql = "UPDATE {$this->_prefix['primary']}order_goods SET `return_goods_status`=3,`return_shipping_id`='" . $return_shipping_id . "',`return_shipping_name`='" . $return_shipping_name . "' WHERE `rec_id`=" . $rec_id;
            $rs  = $this->sql($sql);
            //print_r($sql);die;
            if ($rs) {

                $code = 200;
                $msg  = "填写快递信息成功！";
            }
        } else {

            $code = 405;
        }

        $arr         = array();
        $arr['code'] = $code;
        $arr['msg']  = $msg;
        return $arr;
    }

    //获取所有快递列表
    public function getExpressCompany()
    {
        $sql = "SELECT * FROM {$this->_prefix['primary']}express_company WHERE `stat`=1  ORDER BY `sort` DESC,`id` ASC";
        return $this->sql($sql);
    }

}
